import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Button, Row, Col } from 'antd';
import omit from 'omit.js';
import styles from './index.less';
import map from './map';

const FormItem = Form.Item;

function generator({ defaultProps, defaultRules, type }) {
    return WrappedComponent => {
        return class BasicComponent extends Component {
            static contextTypes = {
                form: PropTypes.object,
                updateActive: PropTypes.func,
                shouldBeInitialized: PropTypes.bool,
            };

            constructor(props) {
                super(props);
                this.state = {
                    count: 0,
                    loading: false,
                };
            }

            componentDidMount() {
                const { updateActive } = this.context;
                const { name } = this.props;
                if (updateActive) {
                    updateActive(name);
                }
            }

            UNSAFE_componentWillReceiveProps(nextProps, context) {
                const { shouldBeInitialized } = context;
                if (shouldBeInitialized) {
                    this.restCaptcha();
                }
            }

            componentWillUnmount() {
                clearInterval(this.interval);
            }

            onGetCaptcha = () => {
                const { form } = this.context;
                form.validateFields(['mobile'], err => {
                    if (err && typeof err.mobile !== 'undefined') {
                        return false;
                    }
                    const { onGetCaptcha } = this.props;
                    const mobile = form.getFieldValue('mobile');
                    if (onGetCaptcha) {
                        this.setState({
                            loading: true,
                        });
                        // 这里得用promise
                        onGetCaptcha({ phone: mobile })
                            .then(ttl => {
                                this.setState({
                                    loading: false,
                                });
                                let count = ttl;
                                this.interval = setInterval(() => {
                                    count -= 1;
                                    this.setState({ count });
                                    if (count === 0) {
                                        clearInterval(this.interval);
                                    }
                                }, 1000);
                            })
                            .catch(e => {
                                this.setState({
                                    loading: false,
                                });
                                this.restCaptcha();
                            });
                    }
                });
            };

            restCaptcha = () => {
                if (this.interval) {
                    clearInterval(this.interval);
                }
                this.setState({ count: 0 });
            };

            render() {
                const { form } = this.context;
                const { getFieldDecorator } = form;
                const options = {};
                let otherProps = {};
                const { onChange, defaultValue, rules, name, ...restProps } = this.props;
                const { count, loading } = this.state;
                options.rules = rules || defaultRules;
                if (onChange) {
                    options.onChange = onChange;
                }
                if (defaultValue) {
                    options.initialValue = defaultValue;
                }
                otherProps = restProps || otherProps;
                if (type === 'Captcha') {
                    const inputProps = omit(otherProps, ['onGetCaptcha']);
                    return (
                        <FormItem>
                            <Row gutter={8}>
                                <Col span={12}>
                                    {getFieldDecorator(name, options)(
                                        <WrappedComponent {...defaultProps} {...inputProps} />
                                    )}
                                </Col>
                                <Col span={12}>
                                    <Button
                                        disabled={count}
                                        className={styles.getCaptcha}
                                        size="large"
                                        onClick={this.onGetCaptcha}
                                        loading={loading}
                                    >
                                        {count ? `${count} s` : '获取验证码'}
                                    </Button>
                                </Col>
                            </Row>
                        </FormItem>
                    );
                }
                return (
                    <FormItem>
                        {getFieldDecorator(name, options)(
                            <WrappedComponent {...defaultProps} {...otherProps} />
                        )}
                    </FormItem>
                );
            }
        };
    };
}

const LoginItem = {};
Object.keys(map).forEach(item => {
    LoginItem[item] = generator({
        defaultProps: map[item].props,
        defaultRules: map[item].rules,
        type: item,
    })(map[item].component);
});

export default LoginItem;
